import localforage from 'localforage';
import { Conversation } from '../models/Conversation.js';
import { Message } from '../models/Message.js';

export class StorageService {
    constructor() {
        this.store = localforage.createInstance({
            name: 'chatbot',
            storeName: 'conversations'
        });
    }

    async initialize() {
        try {
            await this.store.ready();
        } catch (error) {
            console.error('Storage initialization error:', error);
        }
    }

    async saveConversation(conversation) {
        try {
            await this.store.setItem(conversation.id, {
                id: conversation.id,
                title: conversation.title,
                createdAt: conversation.createdAt,
                messages: conversation.messages.map(msg => ({
                    id: msg.id,
                    content: msg.content,
                    sender: msg.sender,
                    timestamp: msg.timestamp
                }))
            });
        } catch (error) {
            console.error('Save conversation error:', error);
        }
    }

    async deleteConversation(conversationId) {
        try {
            await this.store.removeItem(conversationId);
        } catch (error) {
            console.error('Delete conversation error:', error);
        }
    }

    async loadConversations() {
        try {
            const conversations = new Map();
            await this.store.iterate((value, key) => {
                const conversation = new Conversation(value.title);
                conversation.id = value.id;
                conversation.createdAt = new Date(value.createdAt);

                // 重建消息对象
                value.messages.forEach(msg => {
                    const message = new Message(msg.content, msg.sender, new Date(msg.timestamp));
                    message.id = msg.id;
                    conversation.addMessage(message);
                });

                conversations.set(conversation.id, conversation);
            });
            return conversations;
        } catch (error) {
            console.error('Load conversations error:', error);
            return new Map();
        }
    }

    async clearAll() {
        try {
            await this.store.clear();
        } catch (error) {
            console.error('Clear storage error:', error);
        }
    }
}